/* eslint-disable @typescript-eslint/no-unused-vars */
import { Modal, message, PaginationProps } from 'antd';
import { useState, useCallback, useMemo } from 'react';
import { exceptSpace } from '@/utils';
import useUrlQueryRefState from '@/hooks/useUrlQueryRefState';

/**
 * @description: 获取表格相关操作的hooks
 * @param {*} params 一些非表单元素的参数
 * @param {*} api 一些请求的api
 */
export default function useCacheMakeList({ params = {}, api }) {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // --- 列表请求参数 ---
  const [pagination, setPagination] = useUrlQueryRefState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const { total = 0, current = 1, pageSize = 10 } = pagination.current || {};

  // --- 额外的参数，通常是表单元素的值 ---
  const [extraParams, setExtraParams] = useUrlQueryRefState(params);

  // --- 列表 ---
  const [list, setList] = useState([]);

  // --- loading状态 ---
  const [loading, setLoading] = useState(false);
  const [downloadPending, setDownloadPending] = useState(false);

  // --- 处理请求参数 ---
  const getQueryParams = () => {
    return exceptSpace({
      ...extraParams.current,
      current: pagination.current.current || 1,
      pageSize: pagination.current.pageSize || 10,
    });
  };

  //  --- 删除后处理页码 ---
  const calcPageAfterDelete = delCount => {
    setPagination(prev => {
      const newTotal = (prev.total || 0) - delCount;
      let newTotalPages = Math.ceil(newTotal / prev.pageSize);
      newTotalPages = newTotalPages <= 0 ? 1 : newTotalPages;
      return {
        ...prev,
        total: newTotal,
        current: prev > newTotalPages ? newTotalPages : prev,
      };
    });
  };

  // --- 获取表格数据 ---
  const getList = () => {
    setLoading(true);
    api
      .getList(getQueryParams())
      .then(res => {
        if (res.success) {
          setPagination(prev => ({ ...prev, total: res?.data?.total || 0 }));
          let records = [];
          if (res?.data instanceof Array) {
            records = res.data;
          }
          if (res?.data?.records instanceof Array) {
            records = res.data.records;
          }
          setList(
            records.map((item, index) => ({
              ...item,
              __index: (current - 1) * pageSize + index + 1,
            })),
          );
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // --- 批量下载 ---
  const downloadExcel = () => {
    const selections = selectedRowKeys.join(','); // 看接口入参如何命名

    setDownloadPending(true);
    api.downloadExcel?.({ ids: selections, ...getQueryParams() }).finally(() => {
      setDownloadPending(false);
    });
  };

  // --- 删除record ---
  const deleteItem = id => {
    api.deleteItem?.({ id }).then(res => {
      if (res.success) {
        calcPageAfterDelete(1);
        getList();
        message.success('删除成功');
      } else {
        message.error(res.errorMsg || '删除失败');
      }
    });
  };

  // --- 批量删除 ---
  const batchDelete = () => {
    Modal.confirm({
      title: '确认删除',
      content: '是否删除选中数据？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return api
          .batchDelete?.({
            ids: selectedRowKeys.join(','),
          })
          .then(res => {
            if (res.success) {
              calcPageAfterDelete(selectedRowKeys.length);
              getList();
              setSelectedRowKeys([]);
            }
          });
      },
    });
  };

  // --- 行选择配置 ---
  const rowSelection = {
    onChange: keys => {
      setSelectedRowKeys(keys);
    },
    selectedRowKeys,
    preserveSelectedRowKeys: true,
  };

  // --- 分页器设置 ---

  const paginationConfig = {
    total: parseInt(total ?? 0, 10),
    current: parseInt(current, 10),
    pageSize: parseInt(pageSize, 10),
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: () => `共 ${parseInt(total ?? 0, 10)} 条`,
    onChange: (page, size) => {
      setPagination(prev => ({
        ...prev,
        current: size !== parseInt(prev.pageSize, 10) ? 1 : page,
        pageSize: size,
      }));
      getList();
    },
  };

  // --- 清空所选行 ---
  const handleClearSelectedRowKeys = () => {
    setSelectedRowKeys([]);
  };

  return {
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection,
    pagination: pagination.current,
    setPagination,
    paginationConfig,
    extraParams: extraParams.current,
    setExtraParams,
    list,
    setList,
    getList,
    deleteItem,
    batchDelete,
    downloadExcel,
    downloadPending,
    calcPageAfterDelete,
    loading,
    setLoading,
    handleClearSelectedRowKeys,
  };
}
